package com.wujunshen.orika.convert;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.converter.BidirectionalConverter;
import ma.glasnost.orika.metadata.Type;
import org.apache.commons.lang3.exception.ExceptionUtils;

/**
 * @author frank woo(吴峻申) <br>
 * email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2020/2/7 5:33 下午 <br>
 */
@Slf4j
public class JsonConvert<T> extends BidirectionalConverter<T, String> {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    
    @Override
    public String convertTo(T source, Type<String> destinationType, MappingContext mappingContext) {
        try {
            return OBJECT_MAPPER.writeValueAsString(source);
        } catch (JsonProcessingException e) {
            log.error("Exception message is:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }
    
    @Override
    public T convertFrom(String source, Type<T> destinationType, MappingContext mappingContext) {
        try {
            return OBJECT_MAPPER.readValue(source, destinationType.getRawType());
        } catch (IOException e) {
            log.error("Exception message is:{}", ExceptionUtils.getStackTrace(e));
        }
        return null;
    }
}
